using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AutoStopData.Model;
using AutostopDataAccess.Domains;

namespace AutoStopData.Domains
{
    public partial class UserTypes : DomainBase<UserType>
    {
        protected override Dictionary<String, UserType> LoadFromDatabase()
        {
            var ret = new Dictionary<String, UserType>();
            List<UserType> databaseDomains;
            Debug.Write("Loading UserTypes.");
            using (var ctx = new AutoStopContext())
            {
                databaseDomains = ctx.UserTypes.Include(o => o.LocalizableResource.LocalizedResources).ToList();
            }
            foreach (UserType databaseDomain in databaseDomains)
            {
                String key = databaseDomain.UserTypeCode;
                ret.Add(key, databaseDomain);
            }
            Debug.Write("UserTypes loaded.");
            return ret;
        }
        
        public static List<UserTypeLocalized> All()
        {
            var instance = new UserTypes();
            Dictionary<string, UserType> allDomains = instance.CurrentData();
            var retVal = new List<UserTypeLocalized>();
            if (allDomains.Count > 0)
            {
                retVal.AddRange(allDomains.Select(o => new UserTypeLocalized(o.Value)).OrderBy(ol => ol.LocalizedName));
            }
            return retVal;
        }

        public static List<UserTypeLocalized> AllWithBlank()
        {
            var retVal = new List<UserTypeLocalized> { new UserTypeLocalized() };
            retVal.AddRange(All());
            return retVal;
        }
    }

    #region Inner Class

    public class UserTypeLocalized
    {
        public string UserTypeCode { get; set; }
        public string LocalizedName { get; set; }

        public UserTypeLocalized() { }

        public UserTypeLocalized(UserType domain)
        {
            UserTypeCode = domain.UserTypeCode;
            LocalizedName = GetLocalizedData(domain);
        }

        private static String GetLocalizedData(UserType domain)
        {
            String retVal = domain.LocalizableResource.DefaultResourceName;
            const string language = "sk";
            var localizedResource = domain.LocalizableResource.LocalizedResources.FirstOrDefault(lr => lr.CultureCode == language);
            if (localizedResource != null)
            {
                retVal = localizedResource.ResourceName;
            }
            return retVal;
        }
    }

    #endregion
}